package com.been.common.action;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 公共的ACTION层
 * @author been
 * 2011-10-02
 */
public class PublicAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	/**
	 * JSON格式contentType字符串
	 */
	private static final String JSON_CONTENTTYPE_STRING="text/x-json;charset=UTF-8";
	
	/**
	 * Text格式contentType字符串
	 */
	private static final String TEXT_CONTENTTYPE_STRING="text/plain;charset=UTF-8";
	
	/**
	 * HTML格式contentType字符串
	 */
	private static final String HTML_CONTENTTYPE_STRING="text/html;charset=UTF-8";
	
	/**
	 * XML格式contentType字符串
	 */
	private static final String XML_CONTENTTYPE_STRING="text/xml;charset=UTF-8";
	
	/**
	 * 得到当前的请求
	 * @return HttpServletRequest 服务器请求
	 */
	public HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	/**
	 * 得到当前的响应
	 * @return HttpServletResponse 服务器响应
	 */
	public HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	/**
	 * 得到当前服务器请求的会话
	 * @return HttpSession 会话
	 */
	public HttpSession getSession(){
		return getRequest().getSession();
	}
	
	/**
	 * 得到当前程序的上下文
	 * @return ServletContext 上下文
	 */
	public ServletContext getApplication(){
		return ServletActionContext.getServletContext();
	}
	
	/**
     * 直接输出.
     * @param contentType 内容的类型.html,text,xml的值见后，json为"text/x-json;charset=UTF-8"
     * @throws IOException
     */
    public void write(String text, String contentType) throws IOException {
        HttpServletResponse response = getResponse();
        response.setContentType(contentType);
        response.getWriter().write(text);
    }
    
    /**
     * 输出JSON字符串
     * @param strJSON 字符串
     * @throws IOException 异常
     */
    public void writeJSON(String strJSON)throws IOException{
    	this.write(strJSON, JSON_CONTENTTYPE_STRING); 	
    }
    
    /**
     * 输出文本字符串
     * @param strText 字符串
     * @throws IOException 异常
     */
    public void writeText(String strText) throws IOException{
    	this.write(strText, TEXT_CONTENTTYPE_STRING);
    }
    
    /**
     * 输出XML
     * @param strXML 字符串
     * @throws IOException 异常
     */
    public void writeXML(String strXML)throws IOException{
    	this.write(strXML, XML_CONTENTTYPE_STRING);
    }
    
    /**
     * 输出纯HTML.
     * @param strHTML 字符串
     * @throws IOException
     */
    public void writeHTML(String strHTML) throws IOException {
    	this.write(strHTML, HTML_CONTENTTYPE_STRING);
    }
}
